import { Message } from '@arco-design/web-vue'
import type { AxiosResponse } from 'axios'
import axios from 'axios'

export interface HttpResponse<T = unknown> {
	code: string
	message: string
	description: string
	isSuccess: boolean
	data: T
}

export const request = axios.create({
	baseURL: '/api',
	headers: {
		'ngrok-skip-browser-warning': 'true'
	},
	withCredentials: true
})

// request.interceptors.request.use((config) => {
//   config.data = qs.stringify(config.data)
//   console.log(config.data)

//   return config
// }, (error) => { // 请求错误处理
//   Promise.reject(error)
// })

request.interceptors.response.use(
	(response: AxiosResponse<HttpResponse>) => {
		const data: HttpResponse = response.data

		if (data.isSuccess==false) {
			console.log('not success')
			Message.error({
				content: data.message || 'Request Error',
				duration: 5 * 1000
			})
			return Promise.reject(
				new Error(data.message || 'Request Error')
			)
		} else {
			return response
		}
	},
	error => {
		if (error.response.status === 401) {
			console.log('401')
			handle401()
			return Promise.reject(
				new Error(error.response.data.message || 'Request Error')
			)
		}
		Message.error({
			content: error.response.data.message || 'Request Error',
			duration: 5 * 1000
		})
		return Promise.reject(error)
	}
)

function handle401() {
	Message.error({
		content: '用户凭证已失效或未登录',
		duration: 5 * 1000
	})
	// 清除本地用于识别是否登录的cookie
	document.cookie = `login=;expires=${new Date(Date.now() - 1000 * 60 * 60 * 24 * 30).toUTCString()};path=/`
	window.location.href = '/'
}
